package com.tjakus.main;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import com.tjakus.crypto.CryptoManager;
import com.tjakus.logging.Logging;
import com.tjakus.parser.XMLManager;
import com.tjakus.properties.Property;
import com.tjakus.quartz.*;
import com.tjakus.userdata.UserDataList;

public class StartProgram {

	/**
	 * Class which starts RenewAdv application. It initializes crypto manager,
	 * reads properties, reads user data from XML and schedules cron jobs
	 * 
	 * 
	 * @author tjakus
	 * 
	 */

	public static void main(String[] args) throws ClientProtocolException,
			IOException, SchedulerException {

		Logging.getLogger().info("Application - main - [ STARTED ] ");

		// Initialize crypto manager
		try {
			CryptoManager.initializeCryptoManager();
		} catch (Exception e) {
			Logging.getLogger().error(
					"Application - main - [ Unable to initialized Crypto Manager ] ");
			Logging.getLogger().error(e);
			System.exit(1);
		}

		// Initialize all properties
		if (!Property.initializeProperties()) {
			Logging.getLogger().error(
					"Application - main - [ Properties initialization FAILED ] ");
			System.exit(1);
		}

		// Read user data from XML file
		UserDataList.setUserDataList(XMLManager
				.getUserDataFromXmlFile("userdata.xml"));

		if (UserDataList.getUserDataList() == null) {
			Logging.getLogger().error(
					"Application - main - [ Problem reading XML file ] ");
			System.exit(1);
		}

		JobDetail jobReadUserDataJob = JobBuilder.newJob(ReadUserDataJob.class)
				.withIdentity("ReadUserDataJob", "Group2").build();

		JobDetail jobRenewAdvertisementJob = JobBuilder
				.newJob(RenewAdvertisementJob.class)
				.withIdentity("RenewAdvertisementJob", "Group1").build();

		// Trigger ReadUserDataJob
		Trigger triggerForReadUserDataJob = TriggerBuilder
				.newTrigger()
				.withIdentity("ReadUserDataJob", "Group2")
				.withSchedule(
						CronScheduleBuilder.cronSchedule(Property.USER_DATA_CRON_SCHEDULE))
				.build();

		// Trigger RenewAdvertisementJob
		Trigger triggerForRenewAdvertisementJob = TriggerBuilder
				.newTrigger()
				.withIdentity("RenewAdvertisementJob", "Group1")
				.withSchedule(
						CronScheduleBuilder.cronSchedule(Property.RENEW_ADV_CRON_SCHEDULE))
				.build();

		// schedule it
		Scheduler scheduler;
		scheduler = new StdSchedulerFactory().getScheduler();
		scheduler.start();
		scheduler.scheduleJob(jobReadUserDataJob, triggerForReadUserDataJob);
		scheduler.scheduleJob(jobRenewAdvertisementJob,
				triggerForRenewAdvertisementJob);
	}
}
